import 'dart:io';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/provider/global_state_provider.dart';
import 'package:tracker/startup/config/model/global_config_resp.dart';
import 'package:tracker/startup/env/env.dart';
import 'package:tracker/utils/toast_utils.dart';

import '../../common/pay/wxpay_utils.dart';

class AppStart {
  /// 初始化配置
  static Future<void> initConfig() async {
    await WxpayUtils.register();

    EasyRefresh.defaultHeaderBuilder = () {
      return const ClassicHeader(
        dragText: '下拉刷新',
        armedText: '松开刷新',
        readyText: '松开刷新',
        processingText: '加载中...',
        processedText: '加载完成',
        noMoreText: '没有更多数据了',
        failedText: '加载失败',
        messageText: '上次更新时间 %T',
      );
    };
    EasyRefresh.defaultFooterBuilder = () {
      return const ClassicFooter(
        dragText: '上拉加载',
        armedText: '松开加载',
        readyText: '正在加载...',
        processingText: '加载中...',
        processedText: '加载完成',
        noMoreText: '没有更多数据了',
        failedText: '加载失败',
        messageText: '上次更新时间 %T',
      );
    };
  }

  /// 初始化百度地图
  static Future<void> initBaiduMapConfig() async {
    /// 设置用户是否同意SDK隐私协议
    /// since 3.1.0 开发者必须设置
    LocationFlutterPlugin myLocPlugin = LocationFlutterPlugin();
    BMFMapSDK.setAgreePrivacy(true);
    myLocPlugin.setAgreePrivacy(true);

    if (Platform.isAndroid) {
      /// 初始化获取Android 系统版本号，如果低于10使用TextureMapView 等于大于10使用Mapview
      await BMFAndroidVersion.initAndroidVersion();
      BMFMapSDK.setCoordType(BMF_COORD_TYPE.COMMON);
    } else if (Platform.isIOS) {
      myLocPlugin.authAK(Env.envConfig.baiduMapIOSApiKey);
      BMFMapSDK.setApiKeyAndCoordType(Env.envConfig.baiduMapIOSApiKey, BMF_COORD_TYPE.COMMON);
    }
    Map? map = await BMFMapBaseVersion.nativeBaseVersion;
    XLogger.info('获取原生地图版本号：$map');
  }

  /// 初始化全局配置，从服务端获取
  static Future<void> getGlobalConfig(WidgetRef ref) async {
    final res = await get<GlobalConfigResp, GlobalConfigResp>('/config/global', decodeType: GlobalConfigResp());
    res.when(success: (GlobalConfigResp resp) {
      if (resp.code == 200) {
        XLogger.info('获取配置成功');
        ref.read(globalStateProvider.notifier).updateGlobalConfig(resp.data!);
      } else {
        ToastUtils.showToast(resp.msg ?? '获取配置失败');
      }
    }, failure: (String msg, int code) {
      ToastUtils.showToast(msg);
    });
  }
}
